<template>
	<!-- <div @click="reviewShow = false"> -->
	<div>
		<!-- xpert导航栏 -->
		<xpertNavBar :statusTab="statusTab" />
		<div style="height: 150px; width: 100%"></div>

		<div class="income">Income</div>
		<!-- incomeBox -->
		<div class="incomeBox f f-a-c">
			<div class="flexLef f f-d-c f-a-c f-j-c">
				<div class="date">Earnings to date</div>
				<div class="money">$ {{ obj.earnings || 0 }}</div>
			</div>
			<div class="flexLef f f-d-c f-a-c f-j-c">
				<div class="date">Avg. selling price</div>
				<div class="money">$ {{ obj.avgSellingPrice || 0 }}</div>
			</div>
			<div class="flexLef f f-d-c f-a-c f-j-c">
				<div class="date">Order</div>
				<div class="money">{{ obj.orderNum || 0 }}</div>
			</div>
			<div class="flexLef f f-d-c f-a-c f-j-c">
				<div class="date">Earned this month</div>
				<div class="money">$ {{ obj.monthEarned || 0 }}</div>
			</div>
		</div>
		<!-- Overview -->
		<div class="overview m1280">
			<div class="over">Overview</div>
			<!-- tabs -->
			<div class="tabs">
				<Tabs :width="369" @changeTitle="changeTitle" :title="title" :tabList="tabList" />
			</div>
			<div class="date f f-a-c">{{ formatTimestamp(qiTime) }}-{{ formatTimestamp(moTime) }}</div>
			<!-- 下拉 -->
			<div class="reviews hand f f-a-c f-j-b">
				<div @click.stop="reviewShow = !reviewShow" class="rigFilter f f-a-c">Problem ${{ price }}<img src="/src/assets/user/1.png" class="filterImg" alt="" /></div>
				<div v-show="reviewShow" class="reviewsBox">
					<div v-for="(item, index) in sectList" :key="index" @click.stop="reviewCheck(item, index)" class="reviewsBoxitem f f-a-c">
						<div class="leftInp">
							<img src="/src/assets/user/3.png" v-if="item.show" class="inpImg" alt="" />
							<img src="/src/assets/user/4.png" v-else class="inpImg" alt="" />
						</div>
						<div class="rigCount">{{ item.title }}</div>
					</div>
				</div>
			</div>
			<!-- EChact -->
			<div class="echact">
				<EChact ref="echat" />
			</div>
		</div>
		<!-- Reviews -->
		<div class="earning m1280">Earning</div>
		<div class="reviewsss m1280 f f-a-c f-j-b f-w-w">
			<div v-for="(item, index) in listClubl" :key="index" class="lefBox m-b-20 f f-a-c f-j-b">
				<div class="leftCon">
					<div class="top">{{ item.clubName }}</div>
					<div class="count">{{ item.description }}</div>
					<div class="botTime">{{ formatTimestamp(item.createTime) }}</div>
					<div class="earning">Article earning:${{ item.articleIncome || 0 }} Club earning: ${{ item.clubIncome || 0 }}</div>
				</div>
				<div class="imgBox"><img :src="item.clubImage" alt="" /></div>
			</div>
		</div>
		<xpertTabbar />
	</div>
</template>

<script setup>
	import { ref, onMounted, computed } from "vue";
	import xpertTabbar from "@/components/tabBar/xpertTabbar.vue";
	import xpertNavBar from "@/components/navBar/xpertNavBar.vue";
	import { LineChart, OrderStatistics, ClubRevenueStatistics, AllCreateArticleList } from "@/api/knowClub/index.js";
	import router from "@/router/index.js";
	import { ElMessage, dayjs } from "element-plus";
	import { formatTimestamp } from "@/utils/setting.js";
	import Tabs from "@/components/tabs/index.vue";
	import EChact from "@/components/eChactKnow/index.vue";
	import ButtonDiffuse from "@/components/Button/ButtonDiffuse.vue";
	let timeDangqian = ref(+new Date());
	let tab = ref(1);
	let qiTime = ref("2024/5/10");
	let moTime = ref(+new Date());
	let obj = ref({});
	let echat = ref(null);
	let lists = ref([]);
	let statusTab = ref(1);
	let pageNum = ref(1);
	let listClubl = ref([]);
	let price = ref(0);
	let pageSize = ref(100);
	let listPriX = ref([]);
	let articleIds = ref([]);
	let listPriY = ref([]);
	let tabList = ref([
		{ color: "pink", name: "Week", id: "1" },
		{ color: "orange", name: "Month", id: "2" },
		{ color: "green", name: "6 Month", id: "3" },
		{ color: "red", name: "Year", id: "4" }
	]);
	//
	let pro = ref({
		value1: 80,
		value2: 30,
		value3: 10,
		value4: 0,
		value5: 0
	});
	let sectList = ref([
		{
			show: false
		},
		{
			show: false
		},
		{
			show: false
		}
	]);
	let left = ref(0);
	let reviewShow = ref(false);
	let title = ref("Week");

	onMounted(async () => {
		await myCreateArt();
		ClubShows();
		list();
		orderList();
		window.addEventListener("scroll", handleScroll);
	});
	// 我创建的文章
	const myCreateArt = async () => {
		let n = await AllCreateArticleList({
			pageNum: 1,
			pageSize: 100,
			dateSearch:
				tab.value == 1
					? dayjs(getTimestampOneWeekAgo() * 1000).format("YYYY-MM-DD")
					: tab.value == 10
					? dayjs(getTimestampOneWeekAgoMoney() * 1000).format("YYYY-MM-DD")
					: tab.value == 2
					? dayjs(getTimestampOneWeekAgoMoneyLiu() * 1000).format("YYYY-MM-DD")
					: dayjs(getTimestampOneWeekAgoMoneyLius() * 1000).format("YYYY-MM-DD")
		});
		sectList.value = n.data.list.map(item => {
			return { ...item, show: false };
		});
	};
	//俱乐部收入
	const ClubShows = async () => {
		let n = await ClubRevenueStatistics({
			pageNum: pageNum.value,
			pageSize: pageSize.value
		});
		listClubl.value = n.data.list;
	};
	//订单统计
	const orderList = async () => {
		let n = await OrderStatistics();
		obj.value = n.data;
	};
	const list = async () => {
		let n = await LineChart({
			startTime:
				tab.value == 1
					? getTimestampOneWeekAgo() * 1000
					: tab.value == 10
					? getTimestampOneWeekAgoMoney() * 1000
					: tab.value == 2
					? getTimestampOneWeekAgoMoneyLiu() * 1000
					: getTimestampOneWeekAgoMoneyLius() * 1000,
			timeType: tab.value == 10 ? 1 : tab.value == 3 ? 2 : tab.value,
			articleIds: articleIds.value
		});
		// 调用函数
		if (tab.value == 1) {
			let m = generateWeeklyArray(n.data);
			listPriX.value = m.map(item => item.name);
			listPriY.value = m.map(item => item.totalPrice || 0);
			echat.value.timList = listPriX.value;
			echat.value.dataList = listPriY.value;
			echat.value.echat();
			lists.value = m;
			qiTime.value = getTimestampOneWeekAgo() * 1000;
		} else if (tab.value == 10) {
			// 一个月
			let m = generateMonthlyArrays(n.data);
			listPriX.value = m.map(item => dayjs(item.showTime).format("MM/DD"));
			listPriY.value = m.map(item => item.totalPrice || 0);
			echat.value.timList = listPriX.value;
			echat.value.dataList = listPriY.value;
			echat.value.echat();
			lists.value = m;
			qiTime.value = getTimestampOneWeekAgoMoney() * 1000;
		} else if (tab.value == 2) {
			// 6月
			let m = liuyueArrFn(n.data);
			listPriX.value = m.map(item => item.name);
			listPriY.value = m.map(item => item.totalPrice || 0);
			echat.value.timList = listPriX.value;
			echat.value.dataList = listPriY.value;
			echat.value.echat();
			lists.value = m;
			qiTime.value = getTimestampOneWeekAgoMoneyLiu() * 1000;
		} else if (tab.value == 3) {
			// 6月
			let m = liuyueArrFnYarn(n.data);
			listPriX.value = m.map(item => item.name);
			listPriY.value = m.map(item => item.totalPrice || 0);
			echat.value.timList = listPriX.value;
			echat.value.dataList = listPriY.value;
			echat.value.echat();
			lists.value = m;
			qiTime.value = getTimestampOneWeekAgoMoneyLius() * 1000;
		}
	};
	// generateWeeklyArray(dataArray);
	function generateWeeklyArray(dataArray) {
		var timestampArray = getOneWeekAgoDates(); // 使用之前提供的函数获取一周前的时间戳数组
		// console.log(timestampArray, "33333333333333333");
		var resultArray = [];
		for (var i = 0; i < timestampArray.length; i++) {
			var timestamp = timestampArray[i];
			var dayData = dataArray.find(function (item) {
				return item.showTime === getFormattedDate(timestamp);
			});

			var dayName = getDayName(timestamp);
			var totalPrice = dayData ? dayData.totalPrice : "";

			resultArray.push({ name: dayName, totalPrice: totalPrice });
			// console.log(resultArray, "2222222222222222222222222");
		}
		return resultArray;
	}
	// --------------------------------------------------------------------------------------------------------------------------------------------------
	// 给定的数组
	const liuyueArrFn = data => {
		// const data = [
		// 	{ createTime: "2024-04-08 08:07:10", showTime: "2024-04-08", timeType: 1, totalPrice: 2.6 },
		// 	{ createTime: "2024-02-07 08:07:10", showTime: "2024-02-07", timeType: 1, totalPrice: 2.6 },
		// 	{ createTime: "2024-05-05 08:07:10", showTime: "2024-05-05", timeType: 1, totalPrice: 2.6 }
		// ];

		// 生成从今天开始往前推六个月的数组
		const currentDate = new Date(); // 当前日期
		const sixMonthsAgo = new Date(currentDate.getFullYear(), currentDate.getMonth() - 6, 1); // 往前推六个月的日期
		const result = [];

		while (sixMonthsAgo <= currentDate) {
			const month = sixMonthsAgo.getMonth() + 1;
			const year = sixMonthsAgo.getFullYear();
			const monthName = getMonthName(month);

			// 在给定的数组中查找对应月份的数据
			const monthData = data.find(item => {
				const itemDate = new Date(item.showTime);
				return itemDate.getMonth() + 1 === month && itemDate.getFullYear() === year;
			});

			// 构造新的对象
			const newItem = {
				name: monthName,
				showTime: monthData ? monthData.showTime : null,
				totalPrice: monthData ? monthData.totalPrice : null
			};

			result.push(newItem);

			// 前进到下一个月
			sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() + 1);
		}
		return result;
	};
	const liuyueArrFnYarn = data => {
		// const data = [
		// 	{ createTime: "2024-04-08 08:07:10", showTime: "2024-04-08", timeType: 1, totalPrice: 2.6 },
		// 	{ createTime: "2024-02-07 08:07:10", showTime: "2024-02-07", timeType: 1, totalPrice: 2.6 },
		// 	{ createTime: "2024-05-05 08:07:10", showTime: "2024-05-05", timeType: 1, totalPrice: 2.6 }
		// ];

		// 生成从今天开始往前推六个月的数组
		const currentDate = new Date(); // 当前日期
		const sixMonthsAgo = new Date(currentDate.getFullYear() - 1, currentDate.getMonth(), 1); // 往前推六个月的日期
		const result = [];

		while (sixMonthsAgo <= currentDate) {
			const month = sixMonthsAgo.getMonth() + 1;
			const year = sixMonthsAgo.getFullYear();
			const monthName = getMonthName(month);

			// 在给定的数组中查找对应月份的数据
			const monthData = data.find(item => {
				const itemDate = new Date(item.showTime);
				return itemDate.getMonth() + 1 === month && itemDate.getFullYear() === year;
			});

			// 构造新的对象
			const newItem = {
				name: monthName,
				showTime: monthData ? monthData.showTime : null,
				totalPrice: monthData ? monthData.totalPrice : null
			};

			result.push(newItem);

			// 前进到下一个月
			sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() + 1);
		}
		return result;
	};

	// 获取月份对应的名称
	function getMonthName(month) {
		const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
		return monthNames[month - 1];
	}
	// --------------------------------------------------------------------------------------------------------------------------------------------------
	// ==============================================================================================================
	function generateMonthlyArrays(dataArray) {
		var today = new Date(); // 当前日期
		var oneMonthAgo = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate()); // 一个月前的日期
		var resultArray = [];

		while (oneMonthAgo <= today) {
			var formattedDate = getFormattedDates(oneMonthAgo);
			var dayData = dataArray.find(function (item) {
				return item.showTime === formattedDate;
			});

			var dayName = getDayNames(oneMonthAgo);
			var totalPrice = dayData ? dayData.totalPrice : "";

			resultArray.push({ name: dayName, showTime: formattedDate, totalPrice: totalPrice });

			oneMonthAgo.setDate(oneMonthAgo.getDate() + 1); // 递增日期
		}
		return resultArray;
	}
	// 辅助函数：将日期对象转换为指定格式的日期字符串
	function getFormattedDates(date) {
		var year = date.getFullYear();
		var month = ("0" + (date.getMonth() + 1)).slice(-2);
		var day = ("0" + date.getDate()).slice(-2);
		return year + "-" + month + "-" + day;
	}
	// 辅助函数：根据日期获取对应的星期几名称
	function getDayNames(date) {
		var daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
		var dayOfWeek = daysOfWeek[date.getDay()];
		return dayOfWeek;
	}
	// ==============================================================================================================
	function getFormattedDate(timestamp) {
		var date = new Date(timestamp);
		var year = date.getFullYear();
		var month = ("0" + (date.getMonth() + 1)).slice(-2);
		var day = ("0" + date.getDate()).slice(-2);
		return year + "-" + month + "-" + day;
	}
	// 辅助函数：根据时间戳获取对应的星期几名称
	function getDayName(timestamp) {
		var daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
		var date = new Date(timestamp * 1000);
		var dayOfWeek = daysOfWeek[date.getDay()];
		return dayOfWeek;
	}
	function getOneWeekAgoDates() {
		var currentDate = new Date(); // 当前日期
		var oneWeekAgo = new Date(currentDate.getTime() - 7 * 24 * 60 * 60 * 1000); // 一周前的日期
		var dates = [];

		for (var i = 0; i < 7; i++) {
			var date = new Date(oneWeekAgo.getTime() + i * 24 * 60 * 60 * 1000);
			dates.push(date);
		}

		return dates;
	}
	//通过当前时间转为一周前的时间戳
	function getTimestampOneWeekAgo() {
		var now = new Date(); // 获取当前时间
		var oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); // 计算一周前的时间
		let time = Math.floor(oneWeekAgo.getTime() / 1000); // 将时间戳转换为秒并返回
		// getTimestampArrayOneWeekAgo(time);
		return time; // 将时间戳转换为秒并返回
	}
	//通过当前时间转为一个月前的时间戳
	function getTimestampOneWeekAgoMoney() {
		var now = new Date(); // 获取当前时间
		var oneWeekAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000); // 计算一周前的时间
		let time = Math.floor(oneWeekAgo.getTime() / 1000); // 将时间戳转换为秒并返回
		// getTimestampArrayOneWeekAgo(time);
		return time; // 将时间戳转换为秒并返回
	}
	//通过当前时间转为6个月前的时间戳
	function getTimestampOneWeekAgoMoneyLiu() {
		var now = new Date(); // 获取当前时间
		var oneWeekAgo = new Date(now.getTime() - 180 * 24 * 60 * 60 * 1000); // 计算一周前的时间
		let time = Math.floor(oneWeekAgo.getTime() / 1000); // 将时间戳转换为秒并返回
		// getTimestampArrayOneWeekAgo(time);
		return time; // 将时间戳转换为秒并返回
	}
	//通过当前时间转为6个月前的时间戳
	function getTimestampOneWeekAgoMoneyLius() {
		var now = new Date(); // 获取当前时间
		var oneWeekAgo = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000); // 计算一周前的时间
		let time = Math.floor(oneWeekAgo.getTime() / 1000); // 将时间戳转换为秒并返回
		// getTimestampArrayOneWeekAgo(time);
		return time; // 将时间戳转换为秒并返回
	}
	//
	function getTimestampArrayOneWeekAgo(time) {
		var timestampArray = [];
		var oneDayMilliseconds = time; // 一天的毫秒数
		var now = new Date(); // 获取当前时间
		var daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
		for (var i = 0; i < 7; i++) {
			var timestamp = Math.floor((now.getTime() - i * oneDayMilliseconds) / 1000);
			var dayOfWeek = daysOfWeek[(now.getDay() - i + 7) % 7];
			timestampArray.push({ name: dayOfWeek });
		}
		console.log(timestampArray, "111111111111");
		return timestampArray;
	}
	const changeTitle = name => {
		if (name == "Week") {
			tab.value = 1;
		} else if (name == "Month") {
			tab.value = 10;
		} else if (name == "6 Month") {
			tab.value = 2;
		} else {
			tab.value = 3;
		}
		myCreateArt();
		list();
		title.value = name;
	};
	const change = (index, name, id) => {
		// this.nowPage = page;
		// title.value = "";
		setTimeout(() => {
			title.value = name;
		}, 200);
		left.value = index * 25 + "%";
	};
	// 选择
	const reviewCheck = (item, num) => {
		articleIds.value = [];
		sectList.value[num].show = !sectList.value[num].show;
		// console.log(sectList.value, "sectList.value");
		let lists = [];
		sectList.value.forEach(item => {
			if (item.show) {
				lists.push(item);
				articleIds.value.push(item.id);
			}
		});
		// return;
		price.value = lists.map(item => item.price).reduce((a, b) => a + b, 0);
		list();
		// reviewShow.value = false;
	};
	// 这个是当头部导航栏滑倒下面时给tabr加个背景
	const handleScroll = () => {
		const scrollTop = document.documentElement.scrollTop;
		if (scrollTop > 0) {
			statusTab.value = 2;
		} else {
			statusTab.value = 1;
		}
	};
</script>
<style scoped>
	@import "./index.scss";
</style>
